<!--
*@Author: QWP
*@Description: 人员编辑
*@Date: 2023-06-29 17:03:08
-->
<template>
  <u-dialog v-bind="$attrs" @submit="submit" @close="dialgoClose">
    <u-loading-box :loading="loading">
      <u-busi-item title="人员信息" icon="jbxx">
        <u-form :elements="elements" :model="form" ref="formRef">
          <template slot="signPosition">
            <div class="f-flex-column">
              <!-- :src="getFilePath" -->
              <a-image style="width: 100%; height: 68px; cursor: pointer;" fit="contain " :preview="false"
                @click.native="uploadSign">
              </a-image>
            </div>
          </template>
        </u-form>
      </u-busi-item>

      <!-- 角色权限 -->
      <template v-if="roleGroupDatas">
        <a-checkbox-group v-model:value="form.userroles" :options="roleGroupDatas">
          <!-- <a-checkbox 
                  :label="item.keyid" 
                  :value="item.keyid">{{item.rolename}}
                </a-checkbox> -->
        </a-checkbox-group>
      </template>

    </u-loading-box>

    <!-- <template slot="footer" v-if="isCheck == false && form.keyid != ''">
      <u-ptype-button itype="delete" type=" " @click="deleteBtn">删除</u-ptype-button>
      <u-ptype-button itype="refresh">初始化密码</u-ptype-button>
    </template> -->

    <u-uploadE :show="showUpload" :params="fileParams" :multiple="false" @close="showUpload = false"
      @success="uploadCall" />
  </u-dialog>
</template>
<script lang="ts" setup>
import { nullC } from '@/util/common'
import { fileCols } from '@/common/model/fileCols.js'
import * as userService from '@/service/system/user/index'
import * as deptService from '@/service/system/dept/index'
// import * as enumService from '@/service/common/enmu/index'
import * as roleService from '@/service/system/role/index'
import * as userRoleService from '@/service/system/user_role/index'
// import role_mutexService from '@/service/system/role_mutex.service'
// import { fileapi, fileDownload } from '@/http/file'
import { computed, reactive, ref, useAttrs } from 'vue'
import { storeToRefs } from 'pinia'
import { useBaseStore, useLoginStore } from '@/store'
import { alertC, confirmC, isValue } from '@/util/common'
import { watch } from 'vue'
import { commentProps } from 'ant-design-vue/es/comment'

const treeData = ref([]);
const { userInfo } = storeToRefs(useLoginStore());
const { DEPT_TYPE, POST, OVERTIME_EMP_TYPE, STATUS, ROLE_TYPE, POS } = storeToRefs(useBaseStore())
const attrs = useAttrs();
const emit = defineEmits(["success"]);
// const props = defineProps({
//   isCheck: { type: Boolean, default: false},
//     id: { type: String, default: ''},
//     fkunitsid: { type: String, default: ''},
// })

const loading = ref(false)
let form = reactive<any>({
  fkdeptid: '',
  fkunitsid: '',
  loginname: '',
  usercode: '',
  username: '',
  nickname: '',
  gender: '',
  entrydate: '',
  travelstandard: '',
  printposition: '',
  emptype: '',
  userstatus: '',
  businesscard: '',
  businessbank: '',
  paycard: '',
  paybank: '',
  idcard: '',
  tel: '',
  telshort: '',
  remark: '',
  keyid: '',
  signPosition: '',
  userroles: [],
},)

let elements = reactive<any>([
  // {element: 'select', label: '所在单位',  col: { span: 8 }, key: 'fkUnitsId', data: [], required: true,},
  {
    element: 'cascader', label: '所在部门', col: { span: 8 }, key: 'fkdeptid',
    componentProps: {
      options: computed(() => treeData.value), fieldNames: { label: "name", value: "keyid" }, required: true
    }
  },
  {
    element: 'input', label: '登录名', col: { span: 8 }, key: 'loginname',
    componentProps: {
      required: true, maxLength: 50
    }
  },
  {
    element: 'input', label: '人员代码', col: { span: 8 }, key: 'usercode', required: true,
    componentProps: {
      required: true, maxLength: 50, rules: [
        { pattern: /\d+$/g, message: '角色代码只能输入数字!', trigger: 'blur' }
      ]
    }

  },
  {
    element: 'input', label: '人员姓名', col: { span: 8 }, key: 'username',
    componentProps: {
      required: true, maxLength: 50
    }
  },
  {
    element: 'input', label: '昵称/拼音', col: { span: 8 }, key: 'nickname',
    maxlength: "50", 'show-word-limit': true
  },
  {
    element: 'select', label: '性别', col: { span: 8 }, key: 'gender',
    componentProps: { options: computed(() => [{ keyid: '1', name: '男' }, { keyid: '2', name: '女' },]), fieldNames: { label: "name", value: "keyid" }, required: true },

  },
  { element: 'datepicker', label: '入职日期', col: { span: 8 }, key: 'entrydate' },
  {
    element: 'select', label: '差旅标准', col: { span: 8 }, key: 'travelstandard',
    componentProps: {
      options: POST.value, fieldNames: { label: "name", value: "id" }, required: true,
    }

  },
  {
    element: 'select', label: '审核打印位置', col: { span: 8 }, key: 'printposition',
    componentProps: {
      options: POS.value, fieldNames: { label: "name", value: "id" }, required: true,
    }
    // data: POS.value
  },
  {
    element: 'select', label: '人员类型', col: { span: 8 }, key: 'emptype',
    componentProps: {
      options: OVERTIME_EMP_TYPE.value, fieldNames: { label: "name", value: "id" }, required: true
    }
  },
  {
    element: 'select', label: '人员状态', col: { span: 8 }, key: 'userstatus', required: true,
    data: [], baseKey: 'STATUS', props: { label: 'name' },
    componentProps: {
      options: STATUS.value, fieldNames: { label: "name", value: "id" }, required: true,
    }
  },
  {
    element: 'input', label: '公务卡号', col: { span: 8 }, key: 'businesscard',
    maxlength: "50", 'show-word-limit': true
  },
  {
    element: 'input', label: '公务卡银行', col: { span: 8 }, key: 'businessbank',
    maxlength: "50", 'show-word-limit': true
  },
  {
    element: 'input', label: '工资卡号', col: { span: 8 }, key: 'paycard',
    maxlength: "50", 'show-word-limit': true
  },
  {
    element: 'input', label: '工资卡银行', col: { span: 8 }, key: 'paybank',
    maxlength: "50", 'show-word-limit': true
  },
  {
    element: 'input', label: '证件号码', col: { span: 8 }, key: 'idcard',
    maxlength: "50", 'show-word-limit': true
  },
  {
    element: 'input', label: '电话号码', col: { span: 8 }, key: 'tel',
    maxlength: "50", 'show-word-limit': true
  },
  {
    element: 'input', label: '短号', col: { span: 8 }, key: 'telshort',
    maxlength: "50", 'show-word-limit': true
  },
  {
    element: 'textarea', label: '备注', type: 'textarea', col: { span: 16 }, key: 'remark',
    maxlength: "200", 'show-word-limit': true
  },
  // {element: 'upload', label: '签名',  col: { span: 8 }, key: 'signPosition', },
])

const roleGroupDatas = ref()

const fileParams = reactive({
  biztype: '999',
  bucket: 'USER_SIGN',
  moduletype: 'FIN'
})

const showUpload = ref(false)

computed(() => {
  // getFilePath()
})
// const getFilePath =()=> {
//     let signPosition = `${form.signPosition}`;
//     return signPosition.indexOf('127.0') != -1 ? 
//       signPosition.replace(/^http:\/{2}\d+.\d+.\d+.\d+/g, fileDownload) :
//       signPosition
//   }

// 获取部门树形
const getDeptTree = () => {
  loading.value = true;

  deptService.validTree(nullC(attrs.fkunitsid)).then(res => {
    loading.value = false;
    if (res.code == 0) {
      treeData.value = res.data;
      // const index = elements.findIndex(item => item.label == "所在部门")
      // elements.splice(0, 1, { ...elements[index], data: res.data })
    }
  })
    .catch(() => loading.value = false)
}


// 获取枚举数据
const getEnums = () => {
  // const types = [
  //   enumService.types.DEPT_TYPE,
  //   enumService.types.POST,
  //   enumService.types.OVERTIME_EMP_TYPE,
  //   enumService.types.STATUS,
  //   enumService.types.ROLE_TYPE,
  // ]
  loading.value = true;
  // ROLE_TYPE.value.forEach(item => {

  //   roleGroupDatas.value[item.id] = { label: `${item.name}角色` , data: [] }
  //       // this.$set(this.roleGroupDatas, item.id, { label: `${item.name}角色` , data: [] })
  //     })


  // return enumService.enums({types: types.join(',')}).then(res => {
  //   loading = false;
  //   if(res.data.code == '0') {
  //     for(let key in res.data.data) {
  //       let index = this.elements.findIndex(item => item['baseKey'] == key);
  //       if(index != -1) {
  //         this.elements.splice(index, 1, { ...this.elements[index], data: res.data.data[key] })
  //       }
  //     }

  //     res.data.data['ROLE_TYPE'].forEach(item => {
  //       this.$set(this.roleGroupDatas, item.id, { label: `${item.name}角色` , data: [] })
  //     })
  //   }
  // })
  // .catch(() => this.loading = false)
}

// 获取分组角色信息
const getRolesData = async () => {
  if (form.keyid == '') {
    await getEnums();
  }
  roleService.roleGroup().then(res => {
    if (res.code == 0) {
      roleGroupDatas.value = []
      for (let key in res.data) {
        roleGroupDatas.value.push(...res.data[key])
        // if(roleGroupDatas.value[key]) {
        //   roleGroupDatas.value[key]['data'].splice(0, roleGroupDatas.value[key]['data'].length, ...res.data[key]);
        // }
      }
      if (roleGroupDatas.value) {
        roleGroupDatas.value.map(e => {
          e.label = e.rolename
          e.value = e.keyid
        })
      }

    }
  })
    .catch(() => { })
}

const formRef = ref()
// 保存用户提交事件
const submit = () => {
  // 保存时，判断登录名称唯一。
  // 保存时，从角色互斥配置取数，判断某些角色不能设置在同一个用户。
  formRef.value.form.validate().then(async (valid) => {
    // if(!valid) {
    //   alertC("请先将表单必填项填写完毕！");
    //   return
    // }
    loading.value = true;

    // 验证登录名是否可用
    const verifyName = await userService.check({ name: form.loginname });
    if (verifyName.code != 0) {
      alertC(verifyName.data.msg);
      loading.value = false;
      return
    }
    loading.value = false;

    const url = attrs.id == '' ? 'add' : 'update';
    // 修改
    if (attrs.id) {
      form.keyid = attrs.id;
    }
    // 新增
    else {
      form.fkunitsid = attrs.fkunitsid;
    }
    form.fkdeptid = form.fkdeptid[form.fkdeptid.length - 1]
    form.fkunitsid = form.fkunitsid[form.fkunitsid.length - 1]

    loading.value = true;
    userService[url](form).then(res => {
      loading.value = false;
      if (res.code == 0) {
        for (let key in form) {
          if (key != 'userroles') {
            form[key] = nullC(res.data[key])
            // this.$set(this.form, key, this.$common.nullC(res.data.data[key]))
          }
        }
        form.gender += '';
        form.travelstandard += '';
        form.printposition += '';
        form.emptype += '';
        form.userstatus += '';

        alertC(res.msg, 'success');
        emit('success')
      }
      else {
        alertC(res.msg, 'warning');
      }
    })
      .catch(err => {
        loading.value = false;
      })
  }).catch(err => {
    alertC("请先将表单必填项填写完毕！");
    loading.value = false;

  });
}

// 修改回显数据
const echoInfo = async () => {
  loading.value = true;
  // await this.getEnums();
  userService.query(attrs.id).then(res => {
    loading.value = false;
    if (res.code == 0) {
      for (let key in form) {
        if (key != 'userroles') {
          form[key] = nullC(res.data[key])
          // this.$set(this.form, key, this.$common.nullC(res.data.data[key]))
        }
      }
      form.gender += '';
      form.travelstandard += '';
      form.emptype += '';
      form.userstatus += '';
    }
  })
    .catch(() => {
      loading.value = false;
    })
  // return userService
}


// 修改角色信息回显
const echoRoleInfo = async () => {
  loading.value = true;

  userRoleService.rolesByUserId(attrs.id).then(res => {
    loading.value = false;
    if (res.code == 0) {
      form.userroles = res.data
      // this.$set(this.form, 'userroles', res.data.data, [])
    }
  })
    .catch(() => {
      loading.value = false;
    })
}


// 删除用户
const deleteBtn = () => {
  confirmC({ msg: '确认删除?' }).then(() => {

    loading.value = true;
    userService.del({ ids: attrs.id }).then(res => {
      // this.tabLoading = false;
      if (res.code == 0) {
        emit('success')
        alertC(res.msg, "success");
      } else {
        alertC(res.msg, 'warning');
      }
    })
      .catch(err => {
        loading.value = false;
      })

  })
    .catch(() => { })
}

// 上传签名文件
const uploadSign = () => {
  showUpload.value = true;
}

// 附件上传的回调函数
const uploadCall = (file) => {
  form['signPosition'] = file.filepath;
  // this.$set(this.form, 'signPosition', file.filepath)
  showUpload.value = false;
}

// 弹窗关闭
const dialgoClose = () => {
  loading.value = false;
  form['userroles'] = []
  // this.$set(this.form, 'userroles', []);
  formRef.value.form.resetFields();
}


watch(() => attrs.open, (nval) => {
  if (nval == true) {
    getDeptTree()
    getRolesData()
    form.keyid = attrs.id;
    if (attrs.id) {
      echoInfo();
      echoRoleInfo();
    }
  }
}
)
</script>
<style lang='scss'></style>